﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LoRel
{
    public class QuickJoin {
        private readonly Index m_LeftIndex;
        private readonly Index m_RightIndex;
        private readonly CombinedKeySchema m_Schema;
        private readonly Dictionary< Key, JoinClauseMatchSet > m_MatchingClauses;
        

        private readonly Dictionary< Key, BucketTransaction > m_Transactions;
        // This won't work until we fix JoinClauseMatchSet to work on sets of two. Dick.
        public QuickJoin( Index left_index, Index right_index, CombinedKeySchema schema ) {
            m_LeftIndex = left_index;
            m_RightIndex = right_index;
            m_Schema = schema;
            m_MatchingClauses = new Dictionary< Key, JoinClauseMatchSet >();
            m_Transactions = new Dictionary< Key, BucketTransaction >();

            m_LeftIndex.IndexBucketCreated += HandleLeftBucketCreated;
            m_RightIndex.IndexBucketCreated += HandleRightBucketCreated;
        }

        private void HandleRightBucketCreated( Index index, IndexBucket bucket ) {
            
            //BucketTransaction transaction;
            //if( m_Transactions.TryGetValue( bucket.Key, out transaction ) == false ) {
            //    transaction = new BucketTransaction( bucket.Key );
            //    transaction.RHS = bucket;
            //    m_Transactions.Add( bucket.Key, transaction );
            //} else {
            //  JoinClauseMatchSet match = new JoinClauseMatchSet( bucket.Key, m_Schema,
            //      new List< IndexBucket >(){ transaction.LHS, bucket});
            //  m_MatchingClauses.Add(bucket.Key, match);

            //    match.NotifyUniqueKeyAdded += NotifyUniqueKeyAdded;
            //}

        }

        private void HandleLeftBucketCreated( Index index, IndexBucket bucket ) {
            //BucketTransaction transaction;
            //if (m_Transactions.TryGetValue(bucket.Key, out transaction) == false)
            //{
            //    transaction = new BucketTransaction(bucket.Key);
            //    transaction.LHS = bucket;
            //    m_Transactions.Add(bucket.Key, transaction);
            //}
            //else
            //{
            //    JoinClauseMatchSet match = new JoinClauseMatchSet(bucket.Key, m_Schema,
            //        new List<IndexBucket>() { bucket, transaction.RHS });
            //    m_MatchingClauses.Add( bucket.Key, match );
            //    match.NotifyUniqueKeyAdded += NotifyUniqueKeyAdded;
            //}
        }

        public event UniqueKeyAddedHandler NotifyUniqueKeyAdded;
    }
}
